<?php

namespace app\task\service;

use app\task\model\TaskUser;
use app\base\service\BaseService;
use app\base\service\Redis;
use think\facade\Log;

abstract class TaskService 
{	   
    protected $redis="";
    protected $base='';
 	public function __construct()
    {
        $this->redis = Redis::instance(["index" => 0]);
        $this->base =new BaseService;
    }
	// 检查参数
	protected function checkParam($param)
	{
		if (empty($param['taskid']) || empty($param['Openid']))
		{
			return 0;
		}
		else
		{
			return 1;
		}
	}

	// 增加任务
	protected function addUserTask($data)
	{
		unset($data['/task/task/addTask']);
		
		$model = new TaskUser();

		$user_msg = $model->getUserMsg($data['Openid']);

		$data['Cretetime'] = time();
		$data['Token'] = $user_msg['Token'];
		$data['Userid'] = $user_msg['Userid'];

		$res = $model->insert($data);

		return $res;
	}

	// 增加完成的任务
	protected function addTaskComplete($data)
	{
		unset($data['/task/task/complete']);
			
		$model = new TaskUser();

		// 先判断用户是否今天已经完成任务
		$is_complete = $model->isComplete($data['Openid'], $data['taskid']);
		
		// 如果今天已经做了任务，那么无法再次进行
		if (1 == $is_complete)
		{
			return 0;
		}

		$user_msg = $model->getUserMsg($data['Openid']);

		$energy = $model->getEnergy($data['taskid']);

		$data['Token'] = $user_msg['Token'];
		$data['Userid'] = $user_msg['Userid'];
		$data['Cretetime'] = time();
		$data['energy'] = $energy;
		$data['Iscomplete'] = 1;
		$data['currentenergy'] = $energy;
		$data['Completetype'] = 1;

		$res = $model->insertComplete($data);
		return $res;
	}
	//增加催促记录
	protected function addHomeTaskUrge($param)
	{
		$model = new TaskUser();
		$energy = $model->getEnergy($param['taskid']);
		$data = [];
		$data['taskid'] = $param['taskid'];
		$data['Token'] = $param['token'];
		$data['Cretetime'] = time();
		$data['Openid'] = $param['openid'];
		$data['energy'] = $energy;
		$data['Iscomplete'] = 0;
		$data['isUrge'] = 1;
		$data['currentenergy'] = $energy;
		$data['Completetype'] = 1;

		$res = $model->insertComplete($data);
		return $res;
	}
	//发送模板消息'openid': userinfo.Openid,
    //   'taskid': taskid,
    //   'token': userinfo.Token,
	protected function sendMessage($param){
		$model = new TaskUser();
		//获得任务信息
		$access_token = $this->redis->get('access_token');
		//$access_token=$this->get_token();
		if($access_token === false) $access_token=$this->get_token();
		$tasks=$model->get_task($param['taskid']); 

		//通过token获得家庭名称
		$home = $model->get_home($param['token']);

		//获得openid 的集合
		$openids = $model->get_openids($param['token']);

		//循环发送模板消息
		
		foreach ($openids as $k => $v) {
			$post['touser']=$v['Openid'];//openid
			$post['form_id']=$param['formid'];
			$post['taskname']=$tasks['taskname'];//openid
			$post['pdescribe']=$tasks['pdescribe'];
			$post['usernickname']=$home;
			$post['username']=$param['username'];

			$d = $this->sendTemMessage($post);
				log::write("模板信息");
			log::write($d);
		}

	
		
		return $res;
	}

// 标题
// 任务接收通知
// 关键词
// 任务名称
// {{keyword1.DATA}}

// 任务内容
// {{keyword2.DATA}}

// 接受者
// {{keyword3.DATA}}

// 发布者
// {{keyword4.DATA}}

// 发布时间
// {{keyword5.DATA}}

// 备注
// {{keyword6.DATA}}

// 温馨提示
// {{keyword7.DATA}}
	protected function sendTemMessage($post){
		$access_token = $this->redis->get('access_token');
		if($access_token === false) $access_token=$this->get_token();
		$url='https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token;
		$post_data=	'{
	"touser": "'.$post["touser"].'",
	"template_id": "bZ5xoAdWi92NNm6SAdcJdzEcCcDAvhKi8bJtGlr0q6Y",
	"page": "works/work/work",
	"form_id": "'.$post["form_id"].'",
	"data": {
		"keyword1": {
			"value":  "'.$post["taskname"].'"
		},
		"keyword2": {
			"value":   "'.$post["pdescribe"].'"
		},
		"keyword3": {
			"value":   "'.$post["usernickname"].'的家庭"
		},
		"keyword4": {
			"value": "'.$post["username"].'"
		},
		"keyword5": {
			"value": "'.date("Y-m-d H:i:s").'"
		},
		"keyword6": {
			"value": "备注内容"
		},
		"keyword7": {
			"value": "温馨提示"
		}
	}
}';



	$res = $this->base->curlRequest($url,'POST',[],$post_data);
		return $res;

	}
	protected function get_token(){
		//请求access_token
		$url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx6edd9a7d07437495&secret=74be899f3b5c222f2177951967053b51';
		$params='';
		$access_token = $this->base->curlRequest($url,'GET',[],$params);
		$access_token=json_decode($access_token,TRUE);
		//15_a6AfJyWNd3vJnLwGYkEx3Pa4o7s2C1rm9CC0RbTKLZfzNdTAMus9jMnoBeTi2f_jjMIhI6j2wfVP7hWZ0JCI8hKEXS322RdD6jAksERPY1jO8adxAmIwVvoxwHoYJIbABASDC
		$this->redis->set('access_token', $access_token["access_token"], 6000);
		//log::write($this->redis->get('access_token'));
		//log::write( $access_token["access_token"]);
		return $access_token["access_token"];
	}
	// 增加家庭完成的任务
	protected function addHomeTaskRow($param)
	{
		$model = new TaskUser();

		$energy = $model->getEnergy($param['taskid']);
		//判断是否已经被催促，如果被催，则修改记录
		$isUrge = $model->getUrge($param);
		if($isUrge){
			$where['taskid'] = $param['taskid'];
			$where['Token'] = $param['token'];
			$res = $model->updateComplete($where);
		}else{
			$data = [];

		$data['taskid'] = $param['taskid'];
		$data['Token'] = $param['token'];
		$data['Cretetime'] = time();
		$data['Openid'] = $param['openid'];
		$data['energy'] = $energy;
		$data['Iscomplete'] = 1;
		$data['isUrge'] = 0;
		$data['currentenergy'] = $energy;
		$data['Completetype'] = 1;

		$res = $model->insertComplete($data);
		}
		

		// 如果记录添加成功，给家庭养分表中增加能量
		if ($res)
		{	
			$data = [];

			$data['energyInitialNum'] = $energy;
			$data['energyAddTime'] = time();
			$data['energyDesc'] = '蜗牛任务';
			$data['Token'] = $param['token'];
			$data['Openid'] = $param['openid'];
			$data['StealNum'] = 0;
			$data['IsReceive'] = 0;
			$data['energyGetTime'] = '';
			$data['energyEndNum'] = $energy;
			$data['isUse'] = 1;

			$model->insertEnergyTreeRow($data);
		}

		return $res;
	}

	// 得到任务列表
	protected function getList($openid)
	{
		$model = new TaskUser();

		// 先得到已经添加的任务
		$added_task = $model->getAddedTask($openid);

		// 再得到系统推荐的任务(目前是得到还未添加的任务)
		$recom_task = $model->getRecomTask($openid);

		$data = [];

		$data['main_task'] = $added_task;
		$data['recom_task'] = $recom_task;

		return $data;
	}

	// 得到完成任务的列表
	protected function getCompleteList($openid)
	{
		$model = new TaskUser();

		$list = $model->getCompleteList($openid);
		
		return $list;
	}

	// 得到完成家庭任务的列表
	protected function getHomeCList($openid)
	{
		$model = new TaskUser();

		$list = $model->getHomeCompleteList($openid);
		
		return $list;
	}


	// 得到主线任务
	public function getMainList($param)
	{
		$model = new TaskUser();

		$list = $model->getHomeList('main');

		$list = $this->handleHomeList($list, $param);

		return $list;
	}
	//得到催促任务列表
	public function getUrgeList($param){
		$model = new TaskUser();

		$list = $model->getHomeList('urge');

		$list = $this->handleHomeUrgeList($list, $param);

		return $list;
	}
	// 得到推荐任务
	public function getRecomList($param)
	{
		$model = new TaskUser();

		$list = $model->getHomeList('recom');

		$list = $this->handleHomeList($list, $param);

		return $list;
	}

	// 得到树的任务
	public function getTreeList($param)
	{
		$model = new TaskUser();

		$list = $model->getHomeList('tree');

		$list = $this->handleHomeList($list, $param);

		return $list;
	}

	// 处理一下任务列表，判断该家庭是否已经完成任务
	public function handleHomeList($list, $param)
	{
		$model = new TaskUser();
		
		foreach ($list as $k => $v)
		{
			$list[$k]['is_complete'] = $model->isCompleteHome($param['token'], $v['taskid']);
		}

		return $list;
	}


	// 处理一下任务列表，判断该家庭是否已经催促
	public function handleHomeUrgeList($list, $param)
	{
		$model = new TaskUser();
		
		foreach ($list as $k => $v)
		{
			$list[$k]['is_urge'] = $model->isUrgeHome($param['token'], $v['taskid']);
		}

		return $list;
	}
	// 是否完成家庭任务
	public function isCompleteHome($param='')
	{
		$model = new TaskUser();

		$res = $model->isCompleteHome($param['token'], $param['taskid']);

		return $res;
	}
//是否完成催促任务
		public function isUrgeHome($param='')
	{
		$model = new TaskUser();

		$res = $model->isUrgeHome($param['token'], $param['taskid']);

		return $res;
	}
}